import axios from 'axios'
import qs from 'qs'
import router from '../router'
export function request(url, params, method, type, header) {
  let key
  const token = window.localStorage.getItem('token')
  const instance = axios.create({
    baseURL: process.env.VUE_APP_BASE_API,
    timeout: 5000,
    withCredentials: true
  })

  // axios拦截器
  instance.interceptors.request.use((config, err) => {
    if (token !== null) {
      config.headers.common['token'] = token
    }
    return config
  })
  instance.interceptors.response.use((response) => {
    if (response.data.code === 601) {
      return router.push('/login')
    }
    if (response.data.code === 200) {
      return new Promise((resolve, reject) => {
        resolve([null, response.data])
      })
    } else {
      return new Promise((resolve, reject) => {
        resolve([response, null])
      })
    }
  })

  if (method && method === 'post') {
    if (type && type === 'params') {
      console.log(params)
      if (params) {
        // return instance.post(url, params)
        if (header === 'json') {
          return instance.request({
            url,
            data: params,
            method: 'post',
            headers: {
              'Content-Type': 'application/json;charset=UTF-8'
            }
          })
        } else if (type === 'paramsSerializer') {
          return instance.request({
            url,
            data: qs.stringify(params, { arrayFormat: 'repeat' }),
            method: 'post'
          })
        } else {
          return instance.request({
            url,
            data: params,
            method: 'post'
          })
        }
      } else {
        return instance.post(url)
      }
    } else if (type && type === 'row') {
      let query = ''
      for (key in params) {
        query = query + key + '=' + params[key] + '&'
      }
      query = query.slice(0, query.length - 1)
      url = url + '?' + query
      return instance.post(url)
    } else {
      // resful的形式
      if (params) {
        for (const key in params) {
          // 拼接url
          url = url + '/' + params[key]
        }
      }
      return instance.post(url)
    }
  } else if (!method || method === 'get') {
    if (type === 'resful' || !type) {
      // resful的形式
      if (params) {
        for (key in params) {
          // 拼接url
          url = url + '/' + params[key]
        }
      }
      return instance.get(url)
    } else if (type === 'params') {
      params = {
        params: params
      }
      return instance.get(url, params)
    }
  } else if (method && method === 'put') {
    if (params) {
      return instance.put(url, params)
    } else {
      return instance.put(url)
    }
  } else if (method && method === 'delete') {
    // resful的形式
    if (params) {
      for (key in params) {
        // 拼接url
        url = url + '/' + params[key]
      }
    }
    return instance.delete(url)
  }
}
